// pages/taskdetail/taskdetail.js
import {TaskModel} from "../../models/task"
import {CommonModel} from "../../models/common"
import {HTTP} from "../../utils/http"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    task: null,
    custom: Object,
    files: Object,
    finished: '',
    unreadCount: 0,
    countShow: false,
    osstoken: Object,
    ShowSubmitDialog:false,
    ShowGiveUpDialog:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {

    let bid = options.bid
    this.setData({
      finished: options.finished
    })
    const task = await TaskModel.detail(bid)
    task.refund_percent = ((task.refundFee / task.origin_price).toFixed(2) * 100).toString() + '%'
    task.order_desc = task.order_desc.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
    this.setData({
      task: task
    })
    const custom = await TaskModel.custom(bid)
    custom.nick = task.identifier + ':' + custom.nick
    this.setData({
      custom: custom
    })
    const files = await TaskModel.files(bid)
    this.setData({
      files: files
    })

    const osstoken = await CommonModel.oss()
    this.data.osstoken = JSON.parse(osstoken)


    let that = this
    let conversationList_promise = getApp().getIMHandler().tim.getConversationList()
    conversationList_promise.then(function (imResponse) {
      const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
      conversationList.map(item => {
            if (item.conversationID === that.data.custom.conversationID) {
              if (item.unreadCount > 0) {
                that.setData({
                  unreadCount: item.unreadCount,
                  countShow: true
                })
              }
            }
          }
      )
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let conversationList_promise = getApp().getIMHandler().tim.getConversationList()
    conversationList_promise.then(function (imResponse) {
      const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
      conversationList.map(item => {
            if (item.conversationID === that.data.custom.conversationID) {
              if (item.unreadCount > 0) {
                that.setData({
                  unreadCount: item.unreadCount,
                  countShow: true
                })
              }
            }
          }
      )
    }).catch(function (imError) {
      console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
    });
  },


  onUpload: function () {
    let that = this
    let first_options = {
      name:'确认交稿',
      color: '#3683D6'
    }
    if(this.data.task.finished>=1){
      first_options = {
        name:'已交稿',
        color: '#8F8F8F'
      }
    }
    wx.lin.showActionSheet({
      itemList: [
        first_options,
        {
          name: '上传文件'
        },
        {
          name: '上传图片'
        }
      ],
      success(res) {
        if (res.item.name === '确认交稿') {
          that.tasksubmit()
        } else if (res.item.name === '上传文件') {
          that.uploadfile()
        } else if (res.item.name === '上传图片') {
          that.uploadImage()
        }
      },
    })
  },


  uploadfile() {
    let that = this
    wx.chooseMessageFile({
      count: 1,
      extension: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'],
      success: (res) => {
        let filesrc = res.tempFiles[0]
        let timestamp = new Date().getTime()
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: 'http://samereport.oss-cn-beijing.aliyuncs.com',
          filePath: filesrc.path,
          name: 'file',
          formData: {
            name: filesrc.name,
            key: that.data.osstoken.dir + timestamp + '_' + filesrc.name.replace(' ', '_'),
            policy: that.data.osstoken.policy,
            OssAccessKeyId: that.data.osstoken.accessid,
            success_action_status: "200",
            signature: that.data.osstoken.signature
          },
          success: async function (res) {
            const newfile = await TaskModel.savefiles({
              'osskey': that.data.osstoken.dir + timestamp + '_' + filesrc.name.replace(' ', '_'),
              'filename': filesrc.name,
              'task_id': that.data.task.id,
              'size': filesrc.size
            })
            let files = that.data.files
            files.push(newfile)
            that.setData({
              files: files
            })
            wx.hideLoading()
          }
        })
      }
    })
  },

  uploadImage() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let filesrc = res.tempFiles[0]
        let filename = filesrc.path.substr(-10, 10)
        let timestamp = new Date().getTime()
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: 'http://samereport.oss-cn-beijing.aliyuncs.com',
          filePath: filesrc.path,
          name: 'file',
          formData: {
            name: filename,
            key: that.data.osstoken.dir + timestamp + '_' + filename,
            policy: that.data.osstoken.policy,
            OssAccessKeyId: that.data.osstoken.accessid,
            success_action_status: "200",
            signature: that.data.osstoken.signature
          },
          success: async function (res) {
            const newfile = await TaskModel.savefiles({
              'osskey': that.data.osstoken.dir + timestamp + '_' + filename,
              'filename': filename,
              'task_id': that.data.task.id,
              'size': filesrc.size
            })
            let files = that.data.files
            files.push(newfile)
            that.setData({
              files: files
            })
            wx.hideLoading()
          }
        })
      }
    })
  },

  async tasksubmit() {
    const res = await HTTP.request({
      url: 'wx/tasks/submit',
      method: 'POST',
      data: {
        id: this.data.task.id,
      }
    })
    if(res.error_code===0){
      this.setData({
        ShowSubmitDialog:true
      })
    }
  },

  Giveup(){
    this.setData({
      ShowGiveUpDialog:true
    })
  },

  async onGiveUp(){
    const res = await HTTP.request({
      url: 'wx/tasks/giveup',
      method: 'POST',
      data: {
        id: this.data.task.id,
      }
    })
    if(res.error_code===0){
      wx.navigateBack({
        delta: 1
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})